<template>
  <div class="login-account">
    <el-form label-width="60px" :rules="rules" :model="account" ref="formRef">
      <el-form-item label="账号" prop="name">
        <el-input v-model="account.name"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input show-password v-model="account.password"></el-input>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
import { ElForm } from 'element-plus'
import { reactive, ref } from 'vue-demi'
import { defineExpose } from 'vue'
import LocalCache from '@/utils/catch'
import store from '@/store'
const account = reactive({
  name: LocalCache.getCache('name') || '',
  password: LocalCache.getCache('password') || ''
})

const formRef = ref<InstanceType<typeof ElForm>>()
// 父组件点击登录实际执行函数
const loginAction = (isChecked: boolean) => {
  formRef.value?.validate((valid) => {
    if (valid) {
      // 1、判断是否是否勾选了记住密码
      if (isChecked) {
        // 将本地缓存的账号密码缓存到本地
        LocalCache.setCache('name', account.name)
        LocalCache.setCache('password', account.password)
      } else {
        // 当取消勾选记住密码，将本地保存的账号密码删除掉
        LocalCache.deleteCache('name')
        LocalCache.deleteCache('password')
      }
      // 2、开始登录验证
      console.log('通过账号密码发送网络请求')
      store.dispatch('login/accountLoginAction', { ...account })
    }
  })
}
const rules = {
  name: [
    {
      required: true,
      message: '账号是必填的~',
      trigger: 'blur'
    },
    {
      pattern: /^[a-z0-9]{5,10}$/,
      message: '填写长度为5~10位哟~',
      trigger: 'blur'
    }
  ],
  password: [
    {
      required: true,
      message: '密码是必填的',
      trigger: 'blur'
    },
    {
      pattern: /^[a-z0-9]{6,12}$/,
      message: '长度为6~12位~',
      trigger: 'blur'
    }
  ]
}
defineExpose({ loginAction })
</script>

<style scoped lang="less"></style>
